package cc.minos.codec
{
	import flash.utils.ByteArray;
	
	import cc.minos.codec.flv.FlvCodec;
	import cc.minos.codec.mp4.Mp4;
	import cc.minos.codec.mp4.Mp4Codec;
	import cc.minos.codec.mp4.boxs.MoovBox;
	import cc.minos.codec.utils.Log;

	public class MP4Convert
	{
		private var _rawData:ByteArray;
		
		private var moovBox:MoovBox;
		
		private var mp4Codec:Mp4Codec;
		
		private var flvCodec:FlvCodec;
		
		private var mOffset:uint;
		
		public function MP4Convert()
		{
			mp4Codec = new Mp4Codec();
			flvCodec = new FlvCodec();
		}
		
		public function addBytes(byte:ByteArray):Array{
			var result:Array = new Array();
			if(_rawData == null) _rawData = new ByteArray();
			_rawData.position = _rawData.length;
			_rawData.writeBytes(byte);
			_rawData.position = 0;
			
			if(moovBox == null){
				moovBox = getMoovBox(_rawData);
				if(moovBox != null) {
					mp4Codec.initMoovBox(moovBox, _rawData);
					flvCodec.getFlvHeader(result, mp4Codec);
				}
			}
			if(moovBox != null){
				flvCodec.getFlvByteArray(result, mp4Codec);
			}
			return result;
		}
		
		private function getMoovBox(byte:ByteArray):MoovBox{
			var size:uint;
			var type:uint;
			var moovBox:MoovBox;
			byte.position = mOffset;
			while (byte.bytesAvailable > 8)
			{
				mOffset = byte.position;
				size = byte.readUnsignedInt();
				type = byte.readUnsignedInt();
				if (type == Mp4.BOX_TYPE_MOOV)
				{
					var d:ByteArray = new ByteArray();
					try{
						d.writeBytes(byte, mOffset, size);
					}catch(e:Error){
						return null;
					}
					
					Log.info("MoovBox Offset="+mOffset +" Size="+size);
					
					moovBox = new MoovBox();
					moovBox.size = size;
					moovBox.position = mOffset;
					moovBox.parse(d);
					return moovBox;
				}
				byte.position = mOffset + size;
			}
			return null;
		}
		
	}
}